package com.yt.fras.controller;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yt.fras.constant.ResultCode;
import com.yt.fras.pojo.base.JsonResult;
import com.yt.fras.pojo.base.LoginUser;
import com.yt.fras.pojo.entity.User;
import com.yt.fras.service.FaceServer;
import com.yt.fras.service.UserService;
import com.yt.fras.utils.ResultTool;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户模块
 * </p>
 *
 * @author yt
 * @since 2021-10-25
 */
@RestController
@Api(tags = "用户模块")
@RequestMapping("/fras")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private FaceServer faceServer;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 修改密码
     *
     * @param password
     * @return
     */
    @ApiOperation(value = "修改密码")
    @ApiResponses({
            @ApiResponse(code = 200, message = "修改成功！"),
            @ApiResponse(code = 0, message = "修改失败！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    @PutMapping("/user/updatePassword/{password}")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "password", value = "密码", required = true)
    })
    public String updatePassword(@PathVariable String password) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        JsonResult result;
        if (userService.updatePassword(loginUser.getId(), passwordEncoder.encode(password))) {
            result = ResultTool.success();
            result.setMsg("修改成功！");
        } else {
            result = ResultTool.fail();
            result.setMsg("修改失败！");
        }
        return JSON.toJSONString(result);
    }

    /**
     * 更新用户资料
     *
     * @param name
     * @param phone
     * @param email
     * @param introduction
     * @param nickname
     * @param province
     * @param city
     * @return
     */
    @PutMapping("/user/user/{name}/{nickname}/{introduction}/{phone}/{email}/{province}/{city}")
    @ApiOperation(value = "更新用户资料")
    @ApiResponses({
            @ApiResponse(code = 200, message = "修改成功！"),
            @ApiResponse(code = 0, message = "修改失败！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "name", value = "姓名", required = true),
            @ApiImplicitParam(paramType = "path", name = "nickname", value = "昵称", required = true),
            @ApiImplicitParam(paramType = "path", name = "introduction", value = "个人简介", required = true),
            @ApiImplicitParam(paramType = "path", name = "province", value = "省份", required = true),
            @ApiImplicitParam(paramType = "path", name = "city", value = "城市", required = true),
            @ApiImplicitParam(paramType = "path", name = "phone", value = "手机号", required = true),
            @ApiImplicitParam(paramType = "path", name = "email", value = "邮箱", required = true)
    })
    public String updateUser(@PathVariable String nickname, @PathVariable String name, @PathVariable String phone, @PathVariable String email, @PathVariable String introduction, @PathVariable String province, @PathVariable String city) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userService.getById(loginUser.getId());
        user.setNickname(nickname);
        user.setIntroduction(introduction);
        user.setProvince(province);
        user.setCity(city);
        user.setName(name);
        user.setPhone(phone);
        user.setEmail(email);
        JsonResult result;
        if (userService.updateById(user)) {
            result = ResultTool.success();
            result.setMsg("修改成功！");
        } else {
            result = ResultTool.fail();
            result.setMsg("修改失败！");
        }
        return JSON.toJSONString(result);
    }

    /**
     * 更新用户图片
     *
     * @param image
     * @return
     */
    @PutMapping("/user/userImage")
    @ApiOperation(value = "更新用户图片")
    @ApiResponses({
            @ApiResponse(code = 200, message = "修改成功！"),
            @ApiResponse(code = 0, message = "修改失败！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    @ApiImplicitParam(paramType = "body", name = "image", value = "图片base64编码", required = true)
    public String updateUserImage(@RequestParam String image) {

        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        JsonResult result;
        if(StringUtils.isNotBlank(image)){
            String[] split = image.split(",");
            if(split.length>1){
                image=split[1];
            }
            if (faceServer.faceUpdate(loginUser.getId(), image)) {
                result = ResultTool.success();
                result.setMsg("修改成功！");
            } else {
                result = ResultTool.fail();
                result.setMsg("修改失败！");
            }
        }else {
            result = ResultTool.fail();
            result.setMsg("修改失败！");
        }

        return JSON.toJSONString(result);
    }

    /**
     * 验证原密码
     *
     * @param password
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("/user/verifyPassword/{password}")
    @ApiOperation(value = "验证原密码")
    @ApiResponses({
            @ApiResponse(code = 200, message = "原密码正确！"),
            @ApiResponse(code = 0, message = "原密码不正确！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "password", value = "密码", required = true)
    })
    public String verifyPassword(@PathVariable String password) {

        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        JsonResult result = new JsonResult();

        if (passwordEncoder.matches(password, loginUser.getPassword())) {
            result.setSuccess(true);
            result.setMsg("原密码正确！");
            result.setCode(ResultCode.SUCCESS.getCode());
        } else {
            result.setSuccess(false);
            result.setMsg("原密码不正确！");
            result.setCode(ResultCode.COMMON_FAIL.getCode());
        }
        return JSON.toJSONString(result);

    }

    /**
     * 获取用户
     *
     * @return
     */
    @GetMapping("/user/user")
    @ApiOperation(value = "获取用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    public String getUser() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        JsonResult result = ResultTool.success(userService.getUserInfoByUsername(loginUser.getUsername()));
        result.setMsg("获取成功！");
        return JSON.toJSONString(result);
    }

    /**
     * 超级管理员获取用户基本信息集合
     *
     * @return
     */
    @GetMapping("/superadmin/userInfos")
    @ApiOperation(value = "超级管理员获取用户基本信息集合")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功！"),
            @ApiResponse(code = 500, message = "系统出现错误~")
    })
    public String getUserInfoList() {
        JsonResult result = ResultTool.success(userService.getUserInfoList());
        result.setMsg("获取成功！");
        return JSON.toJSONString(result);

    }

}

